import { Badge, Card, message, Table, Row, Col, Button } from 'antd';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import React, { PureComponent } from 'react';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import styles from '../../../components/common/PateoTable/TableList.less';
import SettingModal from './settingModal';

const mapStateToProps = (state:any) => ({
  monitorAlarmSetting: state.monitorAlarmSetting,
  loading: state.loading.models["monitorAlarmSetting"],
});
/**
 * 监控报警设置 页
 */
class MonitorAlarmSetting extends PureComponent<any, any> {
  static contextTypes = {};
  
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      brandList: [],
      vehicleSeriesData: [],
      settingData: {},
      settingModalVisible: false,
      modalType: 'add'
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      page: 1,
      size: 10
    }
    dispatch({
      type: 'monitorAlarmSetting/postFetchPage',
      payload: { url: '/can/op/network/warningconfig/list', ...tempParam },
    });
    //  /newFeedback/findPageList

    this.getBrand()
  }

  //  获取品牌数据
  getBrand = ()=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'connectQuickConfig/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({ brandList: res.data });
        }
      },
    });
  }

  //  获取品牌下车系数据
  getVehicleSeriesData = () => {
    const brandId = this.searchForm.current && this.searchForm.current.getFieldValue('brandId');
    this.searchForm.current && this.searchForm.current.setFieldsValue({
      seriesId: '',
    })
    this.setState({ vehicleSeriesData: [] })
    brandId && this.props.dispatch({
      type: 'vehicleInfoQuery/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({ vehicleSeriesData: res.data });
        }
        /* this.setState({
          vehicleSeriesData: [
            {
              value: '0',
              label: '车系一'
            }
          ]
        }) */
      }
    })
  }

  handleFormReset = () => {
    this.setState({
      formValues: {},
      vehicleSeriesData: []
    });
  }

  handleAdd = () => {
    this.setState({
      settingModalVisible: true,
      modalType: 'add',
    })
  }

  handleEdit = (record: any) => {
    //  编辑
    this.setState({
      settingModalVisible: true,
      settingData: record,
      modalType: 'edit',
    })
  }

  handleRefresh = () => {
    const { dispatch } = this.props;
    this.handleFormReset()
    const tempParam = {
      page: 1,
      size: 10
    }
    dispatch({
      type: 'monitorAlarmSetting/postFetchPage',
      payload: { url: '/can/op/network/warningconfig/list', ...tempParam },
    });
  };

  closeSettingModal = () => {
    this.setState({
      settingModalVisible: false,
      settingData: {},
      modalType: 'add',
    });
  }

  render() {
    const { loading, permissions, monitorAlarmSetting: { pageData: { pagination, rows = []}}, location: { pathname = '/' } } = this.props
    const { formValues, brandList, vehicleSeriesData, settingData, settingModalVisible, modalType } = this.state
    const columns = [
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
      },
      {
        title: '唤醒计数器报警阈值',
        dataIndex: 'wakeupCounterThreshold',
        // render: (text: any) => text == 0 ? '整车网络异常计数' : '唤醒计数'
      },
      /* {
        title: '报警规则',
        dataIndex: 'warningRule',
      }, */
      {
        title: '报警规则',
        dataIndex: 'warningRule',
        render: (text: any) => text == 1 ? '达到阈值时' : '达到阈值倍数时'
      },
      {
        title: '报警频率',
        dataIndex: 'warningFreq',
        render: (text: any) => text == 1 ? '每天' : text == 2 ? '每周' : '每月'
      },
      {
        title: '最大告警次数',
        dataIndex: 'maxWarningCount',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '修改配置',
              key: 'edit',
              auth: 'setting_doEdit',
              // message: '确认？',
              // Popconfirm: true,
              // hide: record.lockStatus !== 1,
              onConfirm: () => { this.handleEdit(record) },
            },
          ]
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        }
      }
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      rowKey: (record: any) => record.sid,
      dataSource: rows,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    }

    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        keyValue: ['brandCode', 'brandName'],
        key: 'brandId',
        onChange: (e: any) => {
          this.getVehicleSeriesData()
        }
      },
      {
        title: '车系',
        type: 'select',
        // customStyle: 6,
        selectOptions: vehicleSeriesData,
        keyValue: ['code', 'name'],
        key: 'seriesId',
      },
    ]

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => this.searchForm = val}
            searchItems={searchItems}
            fetchParams={{ type: 'monitorAlarmSetting/postFetchPage', url: '/can/op/network/warningconfig/list' }}
            extraArgs={{page:1, size:10}}
            saveFormValues={(val:any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
            // handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div>
            <Row>
              <Col span={12}>
                <Button
                  style={{ marginBottom: 8, marginRight: 8 }}
                  type={"primary"}
                  onClick={() => { this.handleAdd() }}
                >
                  新增报警配置
                </Button>
              </Col>
              <Col span={12}></Col>
            </Row>
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'monitorAlarmSetting/postFetchPage', url: '/can/op/network/warningconfig/list', extraArgs: {} }}
            formValues={formValues}
            currentName="page"
            pageSizeName="size"
          />
          <SettingModal 
            onRef={(val: any) => (this.settingModal = val)}
            data={settingData}
            extraData={{
              brandList
            }}
            type={modalType}
            modalVisible={settingModalVisible}
            refresPage={this.handleRefresh}
            closeModal={this.closeSettingModal}
          />
        </Card>
      </div>
    )
  }
}
export default connect(mapStateToProps)(MonitorAlarmSetting);
